package vn.cuhanh;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import vn.cuhanh.bean.Hero;
import vn.cuhanh.bean.ShareInfo;
import vn.cuhanh.dialog.RatingDialog;
import vn.cuhanh.fragment.MenuFragment;
import vn.cuhanh.utils.HelperFunc;
import vn.cuhanh.utils.ShareZingMe;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

public class HeroDetailActivity extends BaseActivity {
	private Hero hero;
	private boolean skillInfoExpanded = false;
	public static int RATING_HERO_REQUEST_CODE = 13;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hero_detail);
		setBehindContentView(R.layout.menu_frame);
		MenuFragment menuFragment = MenuFragment.getInstance(this);
		getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, menuFragment).commit();
		
		Intent intent = getIntent();
		String strHeroInfo = intent.getStringExtra("heroInfo");
		try {
			hero = (Hero) HelperFunc.Deserialize(strHeroInfo);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(hero == null) {
			hero = new Hero();
			hero.setSkillInfo("hero_chanmat_skillinfo.html");
		}
		initButtons();
		initBasicInfo();
		initSkillInfo();
		initSkillGuide();
		initSuggestedItem();
	}
	
	/**
	 * Set buttons event handler
	 */
	private void initButtons() {
		View btnShare = findViewById(R.id.char_info_btn_share);
		btnShare.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(HeroDetailActivity.this, "share", "btn_share_hero_press", "btn_share_hero_press");
				ShareActivity.shareInfo = new ShareInfo(
						getResources().getString(R.string.shareHeroName).replace("hero_name", hero.getName()), 
						getResources().getString(R.string.shareHeroTitle).replace("hero_name", hero.getName()), 
						getResources().getString(R.string.shareHeroDescription)
							.replace("hero_name", hero.getName())
							.replace("funny_phrase", ShareZingMe.getRandomFunnyPhrase(HeroDetailActivity.this)), 
						hero.getAvatarUrl(), 
						hero.getAvatarUrl(), 
						hero.getFullInfoWebUrl(), 
						getResources().getString(R.string.shareHeroState + hero.getId()),
						getResources().getInteger(R.integer.actionIdShareHeroInfo));
				Intent intent = new Intent(HeroDetailActivity.this, ShareActivity.class);
				startActivity(intent);
			}
		});
		
		View btnRate = findViewById(R.id.char_info_btn_rate);
		btnRate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(HeroDetailActivity.this, "hero_activity", "btn_rating_hero_press", "btn_rating_hero_press");
				Intent intentRating = new Intent(HeroDetailActivity.this, RatingDialog.class);
				intentRating.putExtra("heroId", hero.getId());
				startActivityForResult(intentRating, RATING_HERO_REQUEST_CODE);
			}
		});
		if(!MainActivity.isLogin) {
			btnRate.setVisibility(View.GONE);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    if(requestCode == RATING_HERO_REQUEST_CODE) {
	    	if(resultCode == RESULT_OK) {
	    		Timer timer = new Timer();
	    		timer.schedule(new TimerTask() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						updateRatingInfo();
					}
				}, 2000);
	    	}
	    }
	}
	
	/**
	 * 
	 */
	public void initBasicInfo() {
		ImageView avatar = (ImageView) findViewById(R.id.hero_detail_avatar);
		try {
			avatar.setImageBitmap(HelperFunc.getBitmapFromAsset(this, hero.getAvatar()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			HelperFunc.readStackTrace(e);
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		}
		//Name
		TextView txtName = (TextView)findViewById(R.id.hero_detail_display_name);
		txtName.setText(hero.getName());
		//Other Name
		TextView txtOtherName = (TextView)findViewById(R.id.hero_detail_other_name);
		txtOtherName.setText(hero.getOtherName());
		//Rate
		ImageView imageRate = (ImageView)findViewById(R.id.hero_detail_rate);
		String rateFileName = "rating_" + hero.getRate();
		int rateFileNameResId = getResources().getIdentifier(rateFileName, "drawable", getPackageName());
		imageRate.setImageResource(rateFileNameResId);
		//Love rate
		updateRatingInfo();
	}
	
	public void updateRatingInfo() {
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					String url = HeroDetailActivity.this.getResources().getString(R.string.getHeroRatingUrl) + hero.getId();
					String response = HelperFunc.getDataFromSv(url);
					if(response == null) {
						//Log cannot read rating info
						return;
					}
					JSONObject jsonRes = new JSONObject(response);
					int result = jsonRes.getInt("result");
					if(result != 1) {
						return;
					}
					JSONObject data = jsonRes.getJSONObject("ratingInfo");
					double fRate = data.getDouble("rate");
					fRate *= 2;
					final int rate = (int)fRate;
					final int ratingCount = data.getInt("ratingCount");
					HeroDetailActivity.this.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							updateRatingInfoUi(rate, ratingCount);
						}
					});
				} catch (Exception e) {
					// TODO: handle exception
					HelperFunc.readStackTrace(e);
				}
			}
		});
		thread.start();
	}
	
	public void updateRatingInfoUi(int rate, int rateCount) {
		ImageView imageLoveRate = (ImageView)findViewById(R.id.hero_detail_love);
		String loveRateFileName = "heart_" + rate;
		int loveRateFileNameResId = getResources().getIdentifier(loveRateFileName, "drawable", getPackageName());
		imageLoveRate.setImageResource(loveRateFileNameResId);
		//Love rate count
		TextView txtLoveRateCount = (TextView)findViewById(R.id.hero_detail_lovecount);
		txtLoveRateCount.setText(getResources().getString(R.string.hero_rating_count).replace("ratingCount", rateCount + ""));
	}
	
	public void initSuggestedItem() {
		if(hero == null) {
			return;
		}
		String suggestedItemsFileName = hero.getSuggestedItems();
		if(suggestedItemsFileName == null || suggestedItemsFileName.isEmpty()) {
			return;
		}
		WebView skillInfoWebView = (WebView)findViewById(R.id.hero_detail_suggested_item);
		skillInfoWebView.loadUrl("file:///android_asset/" + suggestedItemsFileName);
	}
	
	public void initSkillInfo() {
		if(hero == null) {
			return;
		}
		String skillInfoFileName = hero.getSkillInfo();
		if(skillInfoFileName == null || skillInfoFileName.isEmpty()) {
			return;
		}
		WebView skillInfoWebView = (WebView)findViewById(R.id.hero_detail_skill_info);
		skillInfoWebView.loadUrl("file:///android_asset/" + skillInfoFileName);
//		skillInfoWebView.getSettings().setLoadWithOverviewMode(false);
//		skillInfoWebView.getSettings().setUseWideViewPort(true);
//		skillInfoWebView.getSettings().setBuiltInZoomControls(false);
//		skillInfoWebView.getSettings().setSupportZoom(false);
		int tmp = 200;
		try {
			tmp = skillInfoWebView.getMinimumHeight();
		} catch (NoSuchMethodError e) {
			// TODO: handle exception
			tmp = 200;
		}
		final int minHeight = tmp;
		final ImageView seemore = (ImageView)findViewById(R.id.hero_detail_skill_info_seemore_icon);
		seemore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(HeroDetailActivity.this, "hero_detail_activity", "btn_see_more_skill", "btn_see_more_skill");
				View skillInfoWrapper = findViewById(R.id.hero_detail_skill_info_wrapper);
				if(skillInfoExpanded) {
					HelperFunc.collapse(skillInfoWrapper, minHeight);
					seemore.setImageResource(R.drawable.arrow);
					skillInfoExpanded = false;
				} else {
					HelperFunc.expand(skillInfoWrapper, minHeight);
					seemore.setImageResource(R.drawable.arrow_up);
					skillInfoExpanded = true;
				}
			}
		});
	}
	
	public void initSkillGuide() {
		if(hero == null) {
			return;
		}
		String detailInfoFileName = hero.getDetailInfo();
		if(detailInfoFileName == null || detailInfoFileName.isEmpty()) {
			return;
		}
		WebView detailInfoWebView = (WebView)findViewById(R.id.hero_detail_detail_info);
		detailInfoWebView.loadUrl("file:///android_asset/" + detailInfoFileName);
		int tmp = 200;
		try {
			tmp = detailInfoWebView.getMinimumHeight(); 
		} catch (NoSuchMethodError e) {
			// TODO: handle exception
			tmp = 200;
		}
		final int minHeight = tmp;
		final ImageView seemore = (ImageView) findViewById(R.id.hero_detail_detail_info_seemore_icon);
		seemore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(HeroDetailActivity.this, "hero_detail_activity", "btn_see_more_hero_info", "btn_see_more_hero_info");
				View skillInfoWrapper = findViewById(R.id.hero_detail_detail_info_wrapper);
				if(skillInfoExpanded) {
					HelperFunc.collapse(skillInfoWrapper, minHeight);
					seemore.setImageResource(R.drawable.arrow);
					skillInfoExpanded = false;
				} else {
					HelperFunc.expand(skillInfoWrapper, minHeight);
					seemore.setImageResource(R.drawable.arrow_up);
					skillInfoExpanded = true;
				}
			}
		});
	}
	
	@Override
	public void onResume() {
		super.onResume();
		BaseActivity.updateDndScore(findViewById(R.id.footer));
	}
	
	@Override
	public boolean isShowBackBtn() {
		return true;
	}
	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}
}
